#coding: utf-8

# Copyright (c) P SOFTHOUSE. All rights reserved.

import maya.cmds as cmds  # pylint: disable=E0401
import maya.mel as mel  # pylint: disable=E0401
import json

from PencilLineGuiUtils import *

def initCustomizedAttributeEditor():
    pencilAddMenuPostCommand("addMenu", "pencilUpdateAE")
    cmds.evalDeferred('pcl4ae.pencilUpdateAE()')

def deinitCustomizedAttributeEditor():
    pencilRemoveMenuPostCommand("addMenu", "pencilUpdateAE")

def pencilUpdateAE():
    rootLayout = mel.eval("$temp = $gAERootLayoutName")
    if not cmds.layout(rootLayout, exists=True):
        return

    labelName = "Pencil+ 4"
    cmds.setParent(rootLayout)
    cmds.setParent("addMenu", menu=True)

    menuItems = cmds.menu("addMenu", q=True, ia=True)
    if(menuItems is None):
        return

    node = pencilGetSelectedAETab()
    menuEnable = isMenuEnable(node)
    cmd = getCommand(node)

    visible = 0
    if menuEnable == True:
        visible = cmds.attributeQuery("lineFunctions", n=node, ex=True)
    if cmds.objExists(node) and cmds.nodeType(node) == "PencilMaterial":
        visible = True

    if all( \
     cmds.menuItem(x, q=True, divider=True) \
     or cmds.menuItem(x, q=True, label=True) != labelName \
     for x in menuItems):
         cmds.menuItem(subMenu=True, label=labelName)
         cmds.menuItem(label=getLocalizedString("kPencilLineAddFunctions"), \
                       c=cmd, \
                       en=menuEnable, \
                       cb=visible)

def isMenuEnable(nodeName):
    if not nodeName:
        return False
    # ノードがマテリアルである
    if nodeName in cmds.ls(materials=True):
        # PencilMaterial
        if cmds.nodeType(nodeName) == "PencilMaterial":
            return False
        return True
    # シェーディンググループノードである
    if cmds.nodeType(nodeName, api=True) == "kShadingEngine":
        return True
    return False


def getCommand(nodeName):
    if not nodeName:
        return " "
    # ノードがマテリアルである
    if nodeName in cmds.ls(materials=True):
        return "pcl4ae.changePencilLineFunctionsInMaterial()"
    # シェーディンググループノードである
    if cmds.nodeType(nodeName, api=True) == "kShadingEngine":
        return "pcl4ae.changePencilLineFunctionsInShadingGroup()"
    return " "


def changePencilLineFunctionsInShadingGroup():
    shadingGroupName = pencilGetSelectedAETab()
    mel.eval("PencilLineAELineFunctionLayout_changeLineFunctions()")
    mel.eval("PencilLineAELineFunctionLayout_replace(\"" + shadingGroupName + ".message\")")

def changePencilLineFunctionsInMaterial():
    materialName = pencilGetSelectedAETab()
    mel.eval("PencilLineAEMaterialLineFunctionLayout_changeLineFunctions()")
    mel.eval("PencilLineAEMaterialLineFunctionLayout_replace(\"" + materialName + ".message\")")


def pencilAddMenuPostCommand(menuName, commandName):
    command = createMelCommand(commandName)
    #cmds.menuコマンドで得られるコマンド文字列はダブルクォーテーションがエスケープされていないため、ここでエスケープする
    originalPostCommands = [cmd.replace('"', '\\"')
                                for cmd in cmds.menu(menuName, q=True, pmc=True).split(";")]

    if command in originalPostCommands:
        mel.eval('menu -edit -postMenuCommand "{0}" "{1}"'.format(";".join(originalPostCommands), menuName))
    else:
        originalPostCommands.append(command)
        postCommand = ";".join(originalPostCommands) + ";"
        mel.eval('menu -edit -postMenuCommand "{0}" "{1}"'.format(postCommand, menuName))


def pencilRemoveMenuPostCommand(menuName, commandName):
    command = createMelCommand(commandName)
    originalPostCommand = cmds.menu(menuName, q=True, pmc=True)
    strippedCommand = ";".join(x for x in originalPostCommand.split(";") \
     if x != "" and x != command) \
      + ";"
    cmds.menu(menuName, e=True, pmc=strippedCommand)


def pencilGetSelectedAETab():
    return mel.eval("$temp = $gAECurrentTab")


def createMelCommand(pythonFunctionName):
    return u'python(\\"pcl4ae.{0}()\\")'.format(pythonFunctionName)
